<?php

class Admin_UserController extends My_Controller_Action {

  private $_model;
  private $_controllerName;
  private $_actionName;
  private $_feedback;

  public function init() {
    $template_path = TEMPLATE_PATH . "/admin";
    $this->loadTemplate($template_path, 'template.ini', 'template');

    $this->_model = new Admin_Model_User();

    $this->_controllerName = $this->_request->getControllerName();
    $this->_actionName = $this->_request->getActionName();
    $this->_params = $this->_request->getParams();
    $this->view->params = $this->_params;
    $this->view->controllerName = $this->_controllerName;

    if (in_array($this->_actionName, array('add', 'edit', 'show-all'))) {
      $auth = Zend_Auth::getInstance();
      if ($auth->getIdentity()->Group != 'ADMIN') {
        $this->_redirect('/index/permission');
      }
    }    
  }

  public function indexAction() {  	
    $this->_forward('login');
  }

  public function loginAction() {
    $template_path = TEMPLATE_PATH . "/admin";
    $this->loadTemplate($template_path, 'template.ini', 'login');

    $form = new Admin_Form_Login ();
    $userModel = new Admin_Model_User();

    if ($this->_request->isPost()) {
      $salt = '';
      $formData = $this->_request->getPost();
     
      if ($form->isValid($formData)) {
        $data = $form-> getValues();
        $user = $userModel->getUserByUsername($data['userName']);

        $adapter = new Zend_Auth_Adapter_DbTable($userModel->getAdapter());
        $adapter->setTableName('users')
                ->setIdentityColumn('username')
                ->setCredentialColumn('password')
                ->setCredentialTreatment('?');
        $adapter->setIdentity($data['userName']);
        $adapter->setCredential($data['password']);
        
        if ($user) {
          $salt = $user->salt;
        }
        $adapter->setCredential(md5(md5($data['password']) . $salt));
        
        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($adapter);
        
        if ($result->isValid()) {
          $auth->getStorage()->write(array('username' => $user->userName, 'userId' => $user->uid));
          $redirectUrl = $this->getRequest()->getParam('redirectUrl', '');
          
          if ($redirectUrl != '') {
            $this->_redirect($redirectUrl);
          } else {
            $this->_redirect('/admin');
          }
        }
      }      
      $this->_feedback = 'Tên đăng nhập hoặc mật khẩu không chính xác!';
    }
    $this->view->form = $form;
    $this->view->pageTitle = 'Login';
    $this->view->feedback = $this->_feedback;
  }

  public function logoutAction() {
    $auth = Zend_Auth::getInstance();
    // Delete user session
    $auth->clearIdentity();
    //return $this->_helper->redirector('index', 'user','admin');
    $this->_redirect('/admin/user');
  }

}